<template>
  <xh-container btnText="保存" @onSave="handleClickSubmit" title="绣花检验">
    <view class="container">
      <uni-forms
        ref="form1"
        :rules="rules1"
        :modelValue="formData"
        :label-width="80"
        label-align="right"
      >
        <uni-forms-item required label="检验时间" name="takeBackDate">
          <uni-datetime-picker
            type="date"
            v-model="formData.takeBackDate"
            :start="Date.now()"
          />
        </uni-forms-item>
        <uni-forms-item required label="裁片编号" name="cuttingCode">
          <uni-easyinput disabled v-model="formData.cuttingCode" />
        </uni-forms-item>
        <uni-forms-item required label="工单编号" name="workOrderCode">
          <xh-multiple-select
            v-model="formData.workOrderCode"
            :localdata="workOrderList"
            @change="handleOrderChange"
          ></xh-multiple-select>
        </uni-forms-item>
        <uni-forms-item label="产品名称" name="productName">
          <uni-easyinput disabled v-model="formData.productName" />
        </uni-forms-item>
        <uni-forms-item label="绣花厂" name="embroideryFactory">
          <uni-easyinput disabled v-model="formData.embroideryFactory" />
        </uni-forms-item>
      </uni-forms>
      <uni-section title="新增辅料" type="line">
        <uni-table border stripe emptyText="暂无更多数据">
          <!-- 表头行 -->
          <uni-tr>
            <uni-th
              align="center"
              v-for="item in showColumns"
              :key="item.title"
              >{{ item.title }}</uni-th
            >
          </uni-tr>
          <!-- 表格数据行 -->
          <uni-tr v-for="(item, index) in tableData" :key="index">
            <uni-td align="center">{{ item.badItemLabel }}</uni-td>
            <uni-td align="center">
              {{ item.itemDescLabel }}
            </uni-td>
            <uni-td align="center">{{ item.itemStatusLabel }}</uni-td>
            <uni-td align="center">{{ item.itemNumber }}</uni-td>
            <uni-td align="center">{{ item.workOrderCode }}</uni-td>
            <uni-td align="center">{{ item.imagePath }}</uni-td>
            <uni-td>
              <view class="uni-group">
                <!-- <xh-button size="mini" type="primary"> 修改 </xh-button> -->
                <xh-button
                  size="mini"
                  type="warn"
                  @click="handelClickDel(index)"
                  >删除</xh-button
                >
              </view>
            </uni-td>
          </uni-tr>
        </uni-table>
        <xh-button :borderRadius="0" type="default" @click="handelClickAdd"
          >添加</xh-button
        >
      </uni-section>
      <xh-popup
        title="添加辅料"
        ref="xhPopup"
        @ok="handleClickOk"
        @close="handleClickClose"
      >
        <uni-forms
          ref="form2"
          :modelValue="detailData"
          :label-width="90"
          :rules="rules2"
        >
          <uni-forms-item required label="不良项目" name="badItem">
            <xh-data-select
              v-model="detailData.badItem"
              :localdata="badItemList"
              @change="handleChangeBadItem"
            />
          </uni-forms-item>
          <uni-forms-item label="项目描述" name="itemDesc">
            <xh-data-select
              v-model="detailData.itemDesc"
              :localdata="itemDescList"
              @change="handleChangeDesc"
            />
          </uni-forms-item>
          <uni-forms-item label="状态" name="itemStatus">
            <xh-data-select
              v-model="detailData.itemStatus"
              :localdata="itemStatusList"
            />
          </uni-forms-item>
          <uni-forms-item label="数量" name="itemNumber">
            <uni-easyinput
              type="number"
              v-model="detailData.itemNumber"
              placeholder="请输入数量"
            />
          </uni-forms-item>
          <uni-forms-item label="图片" name="imagePath">
            <xh-image
              :src="detailData.imagePath"
              @onSuccess="handleSuccessImg"
            />
          </uni-forms-item>
        </uni-forms>
      </xh-popup>
    </view>
  </xh-container>
</template>

<script>
import {
  getWorkOrderList,
  addEmbroideryInspect,
  getWorkOrderInfo,
} from "@/api/purchase/pickplanbill.js";
import { formatSelectList } from "@/utils/business.js";
import {
  getBadItemDict,
  getItemStatusDict,
  getItemDescList,
} from "@/api/system/dict.js";

export default {
  data() {
    return {
      formData: {},
      detailData: {},
      tableData: [],
      workOrderList: [],
      rules1: {},
      badItemList: [],
      itemDescList: [],
      itemStatusList: [],
      showColumns: [
        { title: "不良项目" },
        { title: "项目描述" },
        { title: "状态" },
        { title: "数量" },
        { title: "图片" },
        { title: "操作" },
      ],
    };
  },
  computed: {},
  created() {},
  mounted() {},
  onLoad(options) {
    // eslint-disable-next-line no-unused-vars
    const { params, updateBy, updateTime, createBy, createTime, ...rest } =
      options;
    this.formData = rest;
    const { cuttingCode } = rest;
    this.fetchWorkOrderList(cuttingCode);
    this.fetchDict();
  },
  methods: {
    async fetchWorkOrderInfo(workOrderCodes) {
      const { cuttingCode } = this.formData;
      const { data } = await getWorkOrderInfo({
        workOrderCode: workOrderCodes.join(","),
        cuttingCode,
      });
      this.formData = {
        ...this.formData,
        embroideryFactory: data?.embroideryFactory,
      };
    },
    handleOrderChange(val) {
      const arr = val.map((item) => item.value);
      this.fetchWorkOrderInfo(arr);
    },
    handleChangeDesc(item) {
      this.detailData.itemStatus = Number(item.isDefault);
    },
    // 提交
    handleClickSubmit() {
      this.$refs.form1
        .validate()
        .then(() => {
          const { workOrderCode } = this.formData;
          const params = {
            ...this.formData,
            workOrderCode: workOrderCode?.join(","),
            itemList: this.tableData,
          };
          addEmbroideryInspect(params).then(() => {
            this.handleSuccess();
          });
        })
        .catch((err) => {
          console.log("表单错误信息：", err);
        });
    },
    clearData() {
      this.tableData = [];
      this.detailData = {};
      this.formData = {};
    },
    handleSuccess() {
      this.$modal.msgSuccess("操作成功！");
      this.clearData();
      this.$nav.navigateBack();
    },
    handleChangeBadItem(item) {
      const { dictLabel } = item;
      getItemDescList({
        dictLabel,
        dictType: "item_desc",
      }).then((res) => {
        const { rows } = res;
        // dictValue
        this.itemDescList = formatSelectList(rows, "dictValue");
      });
    },
    handleSuccessImg(url) {
      this.detailData = {
        ...this.detailData,
        imagePath: url,
      };
    },
    handleClickOk() {
      this.$refs.form2
        .validate()
        .then(() => {
          const { badItem, itemDesc, itemStatus } = this.detailData;
          const item1 = this.badItemList.find((item) => item.value === badItem);
          const item2 = this.itemDescList.find(
            (item) => item.value === itemDesc
          );
          const item3 = this.itemStatusList.find(
            (item) => item.value === itemStatus
          );
          const tItem = {
            ...this.detailData,
            badItemLabel: item1.text,
            itemDescLabel: item2.text,
            itemStatusLabel: item3.text,
          };
          this.tableData.push(tItem);
          this.detailData = {};
          this.$refs.xhPopup.close();
        })
        .catch((err) => {
          console.log("表单错误信息：", err);
        });
    },
    // 关闭 添加明细弹窗
    handleClickClose() {
      this.$refs.form2.clearValidate();
      this.detailData = {};
    },
    // 添加
    handelClickAdd() {
      this.$refs.xhPopup.open("top");
    },
    // 请求接口-卡号
    fetchWorkOrderList(val) {
      getWorkOrderList(val).then((res) => {
        const { rows } = res;
        this.workOrderList = formatSelectList(rows);
      });
    },
    fetchDict() {
      getBadItemDict().then((res) => {
        const { data } = res;
        this.badItemList = formatSelectList(data, {
          value: "dictCode",
          text: "dictLabel",
        });
      });
      getItemStatusDict().then((res) => {
        const { data } = res;
        this.itemStatusList = formatSelectList(data, {
          value: "dictCode",
          text: "dictLabel",
        });
      });
    },
  },
};
</script>

<style scoped lang="scss">
.container {
  padding: 10px;
}

.popup-title {
  line-height: 45px;
  font-size: 18px;
  font-weight: bold;
  text-align: center;
  height: 45px;
  border-bottom: 1px solid #ccc;
  border-top: 1px solid #ccc;
}

.popup-footer {
  display: flex;

  button {
    flex-grow: 1;
    border-radius: 0;

    &:last-of-type {
      border-left: none;
    }
  }
}

.form-content {
  padding: 10px;
}

.btn-wrapper {
  display: flex;

  button {
    flex-grow: 1;
    border-radius: 0;

    &:last-of-type {
      border-left: none;

      &::after {
        border-left: none;
      }
    }

    &::after {
      border-radius: 0;
    }
  }
}
.img-wrapper {
  height: 60px;
  width: 60px;
  border: 1px solid $uni-border-color;
}
</style>
